﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/*
 *   防止连续跳跃
 * 
 */

public class JumpBox : MonoBehaviour
{
    [Range(0, 10)] public float jumpVelocity = 5f;
    public LayerMask mask;   // 设置对应的碰撞层
    public float boxHeight;

    private Vector2 playerSize;
    private Vector2  boxSize;

    private bool  jumpRequest = false;
    private bool  grounded = false;     // 是否触地

    private Rigidbody2D  _rigidbody2D;

    // Start is called before the first frame update
    void Start()
    {
        _rigidbody2D = GetComponent<Rigidbody2D>();
        playerSize = GetComponent<SpriteRenderer>().bounds.size;
        boxSize = new Vector2(x: playerSize.x * 0.8f, y: boxHeight);
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetButtonDown("Jump") && grounded) 
        {
            jumpRequest = true;
        }
    }

    private void FixedUpdate()
    {
        if (jumpRequest)
        {
            _rigidbody2D.AddForce(Vector2.up * jumpVelocity, ForceMode2D.Impulse);

            jumpRequest = false;
            grounded = false;
        }
        else
        {
            Vector2 boxCenter = (Vector2)transform.position + (Vector2.down * playerSize.y * 0.5f);     // 人物底部中心设置个方框

            if (Physics2D.OverlapBox(boxCenter, boxSize, 0, mask) != null)  // 检测方框用于检测与Bound层和ForeGround层是否重叠，检测是否着地
            {
                grounded = true;
            }
            else
            {
                grounded = false;
            }
        }
    }


    // 显示画框，便于查找错误
    private void OnDrawGizmos()
    {
        if (grounded)
        {
            Gizmos.color = Color.red;
        }
        else
        {
            Gizmos.color = Color.green;
        }

        boxSize = new Vector2(x: playerSize.x * 0.8f, y: boxHeight);     // 物体的宽度和设置的高度
        Vector2 boxCenter = (Vector2)transform.position + (Vector2.down * playerSize.y * 0.5f);
        Gizmos.DrawWireCube(boxCenter, boxSize);
    }

}
